import AsyncStorage from '@react-native-async-storage/async-storage';

const USER_STORE_KEY = 'UserStore.key';
const USER_STORE_DATA = 'UserStore.data';
import {generateRSAKeyPair} from 'WE/Utils';

class UserStore {
  userData = {};
  constructor() {
    const _this = this;
    AsyncStorage.getItem(USER_STORE_KEY).then(
      key => (_this.key = JSON.parse(key)),
    );
    AsyncStorage.getItem(USER_STORE_DATA).then(
      data => (_this.userData = JSON.parse(data)),
    );
  }

  async logout(callback) {
    this.key = undefined;
    this.userData = {};
    await AsyncStorage.clear(callback);
  }

  async getKey() {
    if (this.key) {
      return this.key;
    }
    this.key = JSON.parse((await AsyncStorage.getItem(USER_STORE_KEY)) || '{}');
    return this.key;
  }

  async getKeyOrInit() {
    const parse = await this.getKey();
    if (!parse.public) {
      await this.setKey(await generateRSAKeyPair());
    }
    return this.key;
  }

  async getKeyStringOrInit() {
    const key = await this.getKeyOrInit();
    return {
      privateKey: key.private
        .replace('-----BEGIN RSA PRIVATE KEY-----', '')
        .replace('-----END RSA PRIVATE KEY-----', '')
        .replace(/\n/g, ''),
      publicKey: key.public
        .replace('-----BEGIN RSA PUBLIC KEY-----', '')
        .replace('-----END RSA PUBLIC KEY-----', '')
        .replace(/\n/g, ''),
    };
  }

  async setKey(key) {
    this.key = key;
    await AsyncStorage.setItem(USER_STORE_KEY, JSON.stringify(this.key));
  }

  getSyncToken() {
    return this.userData.token;
  }

  getSyncName() {
    return this.userData?.name;
  }

  async getToken() {
    return this.getUserData().token;
  }

  async getServicePublishKey() {
    return this.getUserData().publicKey;
  }

  async getName() {
    return this.getUserData().publicKey;
  }

  async getUserData() {
    if (this.userData) {
      return this.userData;
    }
    this.userData = JSON.parse(
      (await AsyncStorage.getItem(USER_STORE_DATA)) || '{}',
    );
    return this.userData;
  }

  async saveUserData(data) {
    this.userData = data;
    await AsyncStorage.setItem(USER_STORE_DATA, JSON.stringify(this.userData));
  }
}

export default new UserStore();
